import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_yishop/config/Config.dart';
import 'package:flutter_yishop/constants/Constants.dart';
import 'package:flutter_yishop/pages/tabs/Tabs.dart';
import 'package:flutter_yishop/utils/screen/ScreenAdapter.dart';
import 'package:flutter_yishop/utils/toast_util.dart';
import 'package:flutter_yishop/widget/DialogWidget.dart';
import 'package:flutter_yishop/widget/JDButton.dart';
import 'package:flutter_yishop/widget/JdText.dart';
import 'package:sp_util/sp_util.dart';

class RegisterPage extends StatefulWidget {
  RegisterPage({Key key}) : super(key: key);

  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  Timer _timer;

  //倒计时数值
  var _countdownTime = 0;
  String _tel = ""; //手机号
  String _code = ""; //获取的验证码
  String _inputCode = ""; //输入验证码
  String _password = ""; //密码
  String _confirmPassword = ""; //确认密码

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("注册"),
        actions: <Widget>[
          FlatButton(
            child: Text("客服"),
            onPressed: () {
              ToastUtil.showToasts("客服");
            },
          )
        ],
      ),
      body: Container(
        padding: EdgeInsets.all(ScreenAdapter.width(20)),
        child: ListView(
          children: <Widget>[
            Center(
              child: Container(
                margin: EdgeInsets.only(top: 30),
                height: ScreenAdapter.width(160),
                width: ScreenAdapter.width(160),
                // child: Image.asset('images/login.png'),
                child: Image.asset('assets/images/ic_shop.png'),
                // Image.network(
                //     'https://www.itying.com/images/flutter/list5.jpg',
                //     fit: BoxFit.cover),
              ),
            ),
            SizedBox(height: 30),
            JdText(
              text: "请输入手机号",
              textInputType: TextInputType.phone,
              onChanged: (value) {
                _tel = value;
              },
            ),
            SizedBox(height: 30),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Expanded(
                    child: JdText(
                  text: "请输入验证码",
                  textInputType: TextInputType.number,
                  onChanged: (value) {
                    _inputCode = value;
                  },
                )),
                SizedBox(
                  width: 10,
                ),
                FlatButton(
                  disabledColor: Colors.black12,
                  splashColor: Colors.black12,
                  hoverColor: Colors.redAccent,
                  color: Colors.redAccent,
                  padding: EdgeInsets.only(right: 0),
                  child: Text(_countdownTime > 0?'${_countdownTime}s后重新获取':'获取验证码',
                      style: TextStyle(
                        color: Colors.white,
                      )),
                  onPressed: _countdownTime == 0 ? timePress() : null,
                ),
              ],
            ),
            SizedBox(height: 20),
            JdText(
              text: "请输入密码",
              password: true,
              onChanged: (value) {
                _password = value;
              },
            ),
            SizedBox(height: 20),
            JdText(
              text: "请输入确认密码",
              password: true,
              onChanged: (value) {
                _confirmPassword = value;
              },
            ),
            SizedBox(height: 20),
            JdButton(
              text: "注册",
              color: Colors.red,
              height: 74,
              cb: () {
                validateCode();
              },
            )
          ],
        ),
      ),
    );
  }

  //倒计时事件
  timePress() {
    if (_countdownTime == 0) {
      return () {
        getVerificationCode();
      };
    }
  }

  //倒计时方法
  startCountdown() {
    //倒计时时间
    _countdownTime = 20;
    // print({_countdownTime: _countdownTime, _timer: _timer == null});
    // print(_timer);
    if (_timer == null) {
      //所以第一次循环是_timer是null,再次点击时_timer == null为false
      // print("开启定时器");
      _timer = Timer.periodic(Duration(seconds: 1), (timer){
        if (_countdownTime < 1) {
          // print("定时器取消了");
          _timer.cancel();
          _timer = null;
        } else {
          setState(() {
            _countdownTime -= 1;
          });
        }
      });
      //原因是_timer被赋值了，所以在清除定时器后我手动赋值null
    }
  }

  //获取验证码
  getVerificationCode() {
    RegExp reg = new RegExp(r"^1\d{10}$");
    if (reg.hasMatch(this._tel)) {
      //开始倒计时
      startCountdown();
      Future.delayed(Duration(seconds: 1), () async {
        var api = "${Config.url}api/sendCode";
        var response = await Dio().post(api, data: {"tel": this._tel});
        if (response.data["success"]) {
          //演示直接返回验证码
          DialogWidget.showAlertDialog(context,
              title: "${response.data["message"]}",
              showCancel: false,
              content: "验证码 ${response.data["code"]}");
          _code = response.data["code"];
        } else {
          ToastUtil.showToasts("${response.data["message"]}");
        }
      });
    } else {
      ToastUtil.showToasts("手机号格式不对");
    }
  }

  //验证验证码
  validateCode() async {
    var api = "${Config.url}api/validateCode";
    var response = await Dio()
        .post(api, data: {"tel": this._tel, "code": this._inputCode});
    if (response.data["success"]==true) {
      doRegister();
    } else {
      ToastUtil.showToasts("${response.data["message"]}");
    }
  }

  //注册
  doRegister() async {
    if (_password.length < 6) {
      ToastUtil.showToasts("密码长度不小于6位");
    } else if (_password != _confirmPassword) {
      ToastUtil.showToasts("密码不一致");
    } else {
      var api = "${Config.url}api/register";
      var response = await Dio().post(api, data: {
        "tel": this._tel,
        "code": this._inputCode,
        "password": this._password
      });
      if (response.data["success"]) {
        SpUtil.putObjectList(Constants.USERINFO, response.data["userinfo"]);
        print('userinfo:${SpUtil.getObjectList(Constants.USERINFO)}');
        //返回到根
        Navigator.of(context).pushAndRemoveUntil(
            new MaterialPageRoute(builder: (context) => Tabs(index: 3,)),
            (route) => route == null);
      } else {
        ToastUtil.showToasts("${response.data["message"]}");
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      // print("销毁啦");
      _timer.cancel();
    }
  }
}
